<template>
  <div class="container-xl containermain bg-white">
    <div class="row">
      <h4 class="col h">题目列表</h4>
    </div>
    <div class="row" :style="{ marginBottom: '24px' }">
      <div style="padding-left: 48px; width: 600px">
        <div>
          <div style="border-radius: 2px 0px 0px 2px" @click="activeName = 'public'"
            :class="activeName == 'public' ? 'div-success' : 'div-info'" class="d-inline-block div-a1">公开题目</div>
          <div v-if="getuser" @click="activeName = 'team'" style="border-radius: 0px 2px 2px 0px"
            :class="activeName == 'team' ? 'div-success' : 'div-info'" class="d-inline-block div-a1">团队题目</div>
          <div v-if="getuser && showCF(teamId) || showRemotejudge" @click="activeName = 'codeforces'"
            style="border-radius: 0px 2px 2px 0px" :class="activeName == 'codeforces' ? 'div-success' : 'div-info'"
            class="d-inline-block div-a1">CODEFORCES
          </div>
          <div v-if="getuser?.uservip?.find(c => c.viplistid === 1)" @click="activeName = 'match'"
            style="border-radius: 0px 2px 2px 0px" :class="activeName == 'match' ? 'div-success' : 'div-info'"
            class="d-inline-block div-a1 "><img width="20"
              src="https://cdn-hterobot.oss-cn-qingdao.aliyuncs.com/JOY/oj_1_1/vip.svg" class="vip" /> 精选题目
          </div>
          <div v-if="getuser" @click="activeName = 'user'" style="border-radius: 0px 2px 2px 0px"
            :class="activeName == 'user' ? 'div-success' : 'div-info'" class="d-inline-block div-a1">我的题目
          </div>
        </div>
      </div>

      <div class="col text-right">
        <el-form :inline="true" label-width="80px" :model="formInline">
          <el-form-item label="我的团队" :style="{ marginBottom: '0' }" v-if="activeName == 'team'">
            <el-select multiple collapse-tags v-model.lazy="formInline.teamid" :style="{ minWidth: '300px' }">
              <el-option v-for="item in getteam" :key="item.ID" :label="item.name" :value="Number(item.ID)"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <el-form :style="{ padding: '0px 40px' }" :inline="false" label-position="left">
      <el-form-item size="default" class="question-header2" label="查找题目" :label-width="120">
        <el-input size="default" :style="{ width: '300px' }" v-model.lazy="formInline.name" placeholder="输入题目名或ID搜索">
          <template #append>
            <el-button @click="start" :style="{ backgroundColor: '#000', color: '#fff' }" :icon="Search" />
          </template>
        </el-input>
      </el-form-item>
      <el-form-item size="default" class="question-header2" label="难度" :label-width="60">
        <el-button @click="formInline.difficulty = []"
          :type="Boolean(formInline.difficulty?.length) ? 'default' : 'primary'"
          :text="Boolean(formInline.difficulty?.length)" size="small">全部</el-button>
        <el-button @click="DATAdifficultyclick(key)"
          :type="formInline.difficulty?.includes(key) ? 'primary' : 'default'"
          :text="!formInline.difficulty?.includes(key)" v-for="(item, key) in DATAdifficulty" :key="item"
          size="small">{{
            item }}</el-button>
      </el-form-item>
      <el-form-item size="default" class="question-header2" label="知识点" :label-width="76">
        <div>
          <el-tag size="default" effect="dark" v-for="(tag, i) in setlabel" :key="i" class="mx-1" closable
            @close="() => { setlabel.splice(i, 1); start() }">
            {{ getlabel.find(e => e.ID === tag)?.name }}
          </el-tag>
        </div>
        <el-button @click="dialogVisible = true" type="primary" plain :style="{ margin: '0px 4px' }"
          size="small">筛选知识点</el-button>
      </el-form-item>
    </el-form>
    <div class="row" :style="{ marginBottom: '24px' }">
      <div class="col" :style="{ paddingLeft: '48px' }">
        共计{{ getquestioncount }}条结果
      </div>
      <div class="col text-right" :style="{ paddingRight: '48px' }">
        <span class="cu" @click="reset" :style="{
          color: 'rgba(0, 0, 0, 0.45)'
        }">清除所有筛选条件</span>
      </div>
    </div>
    <div class="row min-height" v-loading="loading">
      <div class="col" :style="{ padding: '0 24px 0 24px' }">
        <table class="table table-borderless table-hover table-striped">
          <thead class="border-bottom thead">
            <tr>
              <td width="80" scope="col" class="m-pl-6 m-border-2">状态</td>
              <td width="80" scope="col">编号</td>
              <td scope="col">题目</td>
              <td width="300">知识点</td>
              <td width="100">难度</td>
              <td width="160">来源</td>
              <td width="160" v-if="activeName === 'match'">来源明细</td>
              <td width="80" v-if="activeName !== 'match'">AC次数</td>
              <td width="80" v-if="activeName !== 'match'">提交次数</td>
              <td width="80" class="m-border-2 m-pr-6 text-right" v-if="activeName !== 'match'">AC率</td>
              <td width="80" v-if="activeName === 'user'" class="text-center">操作</td>
            </tr>
          </thead>
          <tbody>
            <router-link v-for="(v, key) in getquestion" :key="key" :to="{
              name: '题目',
              params: { ID: v.ID },
              query: { order, offset, limit, teamid: activeName === 'team' ? formInline.teamid.length ? formInline.teamid : getteam?.map((v) => v.ID) : null, name: formInline.name, range: activeName, },
            }" custom v-slot="{ navigate }">
              <tr class="cu" @click="navigate">
                <td class="m-pl-6 m-border-2">
                  <el-icon :color="Number(v.myACcount) ? 'var(--color-cheng)' : 'var(--color-43)'">
                    <Select v-if="Number(v.myACcount)" />
                    <CloseBold v-else-if="Number(v.myUNcount)" />
                    <SemiSelect v-else />
                  </el-icon>

                </td>
                <td v-text="v.ID"></td>
                <td v-text="v.name"></td>
                <td>
                  <div class="question-label">
                    <el-tag text plain size="small" class="el-tag" v-for="(vo, keys) in v.questionlabel"
                      v-text="getlabel.find(e => e.ID === vo.labelid)?.name" :key="`1-${keys}`"
                      @click.stop="getlabelpid(vo.labelid)"></el-tag>
                    <!-- <el-button type="primary" plain size="small" v-for="(vo, keys) in v.questionlabel"
                      v-text="getlabel.find(e => e.ID === vo.labelid)?.name" :key="`1-${keys}`"
                      @click.stop="getlabelpid(vo.labelid)"></el-button> -->
                  </div>
                </td>
                <td>
                  <div v-if="v.difficulty" :class="`difficulty-${v.difficulty}`">{{ v.difficulty ?
                    DATAdifficulty[v.difficulty] : '' }}</div>
                </td>
                <td width="160">{{ v.source }}</td>
                <td width="160" v-if="activeName === 'match'">
                  {{ v.goldremarks }}
                </td>
                <td v-if="activeName !== 'match'">{{ v.ACcount || 0 }}</td>
                <td v-if="activeName !== 'match'">{{ v.userquestioncount || 0 }}</td>
                <td class="m-border-2 m-pr-6 text-right" v-if="activeName !== 'match'">{{ v.userquestioncount ?
                  Math.floor(Number(v.ACcount || 0) /
                    Number(v.userquestioncount) * 100) : 0 }}%
                </td>
                <td class="text-center" v-if="activeName === 'user'">
                  <router-link custom :to="{ name: '修改我的题库', query: { ID: v.ID } }" v-slot="{ navigate }">
                    <el-button size="default" @click.stop="navigate">编辑</el-button>
                  </router-link>
                </td>
              </tr>
            </router-link>
          </tbody>
        </table>
      </div>
    </div>
    <div class="row">
      <div class="col text-right">
        <el-pagination :page-size="limit" :total="getquestioncount" @current-change="change" layout="prev, pager, next"
          :current-page="Math.floor(offset / limit) + 1"></el-pagination>
      </div>
    </div>
    <el-dialog v-model="dialogVisible" title="选择知识点" width="840px" :before-close="start">
      <selectlabelVue @update:label="e => setlabel = e" :label="setlabel"></selectlabelVue>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="dialogVisible = false; start()">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { CloseBold, Search, Select, SemiSelect } from '@element-plus/icons-vue';
import { debounce } from "underscore";
import { computed, onMounted, reactive, ref, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useStore } from "vuex";
import { Iobj } from '../../../api';
import selectlabelVue from '../../../components/selectlabel/index.vue';
import { Storekey } from '../../../interface';
import Studycodemodel from '../../../mysql_interface/studycodemodel';
import { showCF } from '../../../util/data';
import { DATAdifficulty } from '../../data/data';

const activeName = ref<Studycodemodel.Iquestion['range']>('public')
const formInline = reactive<Iobj<Studycodemodel.Iquestion>>({
  teamid: [],
  name: "",
  label: "",
})
const loading = ref(true)
const setlabel = ref<number[]>([])
const store = useStore(Storekey)
const router = useRouter()
const getquestion = computed(() => {
  return store.state.question?.rows || []
})
const console = window.console
const dialogVisible = ref(false)
const getquestioncount = computed(() => {
  return store.state.question?.count || 0
})
const getuser = computed(() => {
  return store.state.user
})
const teamId = computed(() => {
  return Number(getuser.value?.teamid)
})
const getteam = computed(() => {
  return store.state.team?.rows || []
})
const showRemotejudge = computed(() => {
  return getteam.value.some(c => c?.other?.showRemotejudge)
})
const getlabel = computed(() => {
  return store.state.label?.rows || []
})
const route = useRoute()
const roue = computed(() => {
  return route.query as Record<string, string>
})


const order = computed(() => {
  return (roue.value.order || 'ID') as string as keyof Studycodemodel.Iquestion
})

const offset = computed(() => {
  return Number(roue.value.offset) || 0
})

const limit = computed(() => {
  return Number(roue.value.limit) || 20
})

const sortable = computed(() => {
  return (roue.value.sortable || 'ASC') as "DESC" | "ASC"
})


function reset() {
  formInline.name = undefined
  formInline.difficulty = undefined
  setlabel.value = []
  start()
}


watch(() => route.query, () => {
  if (route.name === '题库') {
    start()
  }
})

watch(() => activeName.value, async (e) => {
  if (e) {
    await router.push({
      query: {
        order: "ID",
        offset: 0,
        limit: 20,
      },
    })
  }
  start()
})

watch(formInline, () => {
  start()
})

const debouncet1 = ref<Function>()
onMounted(() => {
  store.dispatch("actionlabel")
  debouncet1.value = debouncet();
  start()
})

function debouncet() {
  return debounce(async () => {
    const { name, teamid } = formInline;
    const obj: Iobj<Studycodemodel.Iquestion> = {
      _order: order.value,
      _offset: offset.value,
      _limit: limit.value,
      _sortable: sortable.value,
    };
    let _like: [keyof Studycodemodel.Iquestion, any]
    if (name) {
      _like = ["name", formInline.name];
      const id = Number(name);
      if (id == name) {
        _like = ["ID", id];
      }
      obj._like = _like;
    }
    let t;
    if (activeName.value === "public") {
      obj.range = 'public';
    } else if (activeName.value === "codeforces") {
      obj.range = 'codeforces'
    } else if (activeName.value === 'match') {
      obj.range = 'match'
    } else if (activeName.value === 'user') {
      obj.range = 'user'
      obj.userid = getuser.value?.ID
    } else {
      t = teamid.length ? teamid : getteam.value?.map((v) => v.ID);
      obj.teamid = t;
    }
    if (!obj.range) {
      obj.range = 'public'
    }

    if (Array.isArray(formInline.difficulty) && formInline.difficulty.length) {
      obj.difficulty = formInline.difficulty
    }
    if (setlabel.value && setlabel.value.length) {
      if (!obj._include) obj._include = {};
      obj._include.questionlabel = [
        "labelid",
        setlabel.value,
      ];
    }
    loading.value = true;
    await store.dispatch("actionquestion", obj);
    loading.value = false;
    // nextTick(() => {
    //   document.getElementById('mycascader')
    // })
  }, 300);
}

function start() {
  dialogVisible.value = false
  if (debouncet1.value) {
    debouncet1.value()
  }
}


function DATAdifficultyclick(item: string) {
  if (!Array.isArray(formInline.difficulty)) formInline.difficulty = []
  const i = formInline.difficulty.findIndex((e: string) => e === item)
  console.log(i)
  if (i != -1) {
    formInline.difficulty.splice(i, 1)
  } else {
    formInline.difficulty.push(item)
  }
}

function grouplabelclick(item: number) {
  if (!Array.isArray(setlabel.value)) setlabel.value = []
  const i = setlabel.value.findIndex(e => e === item)
  if (i != -1) {
    setlabel.value.splice(i, 1)
  } else {
    setlabel.value.push(item)
  }
}

function change(r: number) {
  router.push({
    name: "题库",
    query: {
      limit: limit.value,
      order: order.value,
      offset: (r - 1) * limit.value,
      _sortable: sortable.value,
    },
  });
}



function getlabelpid(pid?: number) {
  if (pid) {
    setlabel.value = [pid]
    start()
  }
}

</script>


<style scoped>
.containermain {
  padding-bottom: 24px;
  margin-bottom: 48px;
  margin-top: 24px;
}

.min-height {
  min-height: 50vh;
}

.min-height button {
  padding: 3px 8px;
  font-size: 12px;
}

tr {
  line-height: 48px;
}

td {
  padding: 0 !important;
}

.div-a1 {
  width: 104px;
  height: 40px;
  text-align: center;
  line-height: 40px;
  cursor: pointer;
  position: relative;
}

.h {
  font-weight: bold;
  font-size: 32px;
  margin-bottom: 48px;
  margin-top: 48px;
  padding-left: 48px;
  padding-right: 48px;
}

.m-pl-6 {
  padding-left: 24px !important;
}

.m-pr-6 {
  padding-right: 24px !important;
}

.div-success {
  background-color: var(--color-43);
  color: #ffffff;
}

.div-info {
  background-color: #d9d9d9;
  color: #8c8c8c;
}

.question-label {
  overflow: hidden;
  height: 48px;
  display: flex;
  flex-wrap: wrap;
  gap: 2px;
  align-items: center;
  --el-color-primary-light-8: var(--color-cheng);
}

.question-header {
  font-weight: 400;
  --el-form-label-font-size: 24px;
  --color-43: #000;
  margin-bottom: 0;

}

.question-header2 {
  font-weight: 700;
  --el-form-label-font-size: 16px;
  --color-43: #000;
  margin-bottom: 20px;
  text-align: left;
}

.question-header2 .el-button.is-text {
  border-width: 1px;
}

table td {
  text-overflow: ellipsis;
  overflow: hidden;
  word-break: break-all;
  white-space: nowrap;
}
</style>


<style>
.radio123 .el-radio__label {
  display: none;
}

.el-cascader-node.is-selectable.in-active-path {
  background-color: var(--color-f5);
}

#mycascader .icon-circle-close {
  font-size: 20px;
}

.el-cascader-menu__list {
  width: 300px;
  flex: 1;
  border-left: 1px solid #aaa;
}

.el-cascader-node__label:hover {
  color: var(--color-cheng);
}

.el-cascader-menu__wrap {
  height: 360px !important;
}
</style>
